<template>
  <div>
    <basic-container>
      <!--当前offer状态-->
      <div class="offer-warning">
        当前订单: {{ offer }}【{{(offerInfo)?offerInfo.name:'---'}}】 处于{{getOfferStatusText()}}状态
      </div>
      <!-- 订单折线图-->
      <div id="offerLine" :style="{width:'100%',height:'400px'}"></div>
    </basic-container>

    <!--账户昨日数据-->
    <basic-container>
      <div class="welLabel">账户昨日数据 <span class="lastDayStyle">({{ yesterday }})</span></div>
      <div>
        <el-table  :default-sort = "{prop: 'cost', order: 'descending'}" :data="accountDataList" stripe style="width: 100%" height="250">
          <el-table-column prop="accountName" label="账户名称"/>
          <el-table-column prop="installs" label="安装" sortable :sort-method="(a,b)=>{return a.installs[0] - b.installs[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.installs[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.installsIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.installsIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="installsIncrease" label="涨幅" sortable :sort-method="(a,b)=>{return a.installsIncrease - b.installsIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.installsIncrease)}">
                {{ scope.row.installsIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="花费" sortable :sort-method="(a,b)=>{return a.cost[0] - b.cost[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.cost[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.costIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.costIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="costIncrease" label="涨幅" sortable :sort-method="(a,b)=>{return a.costIncrease - b.costIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.costIncrease)}">
                {{ scope.row.costIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </basic-container>

    <!--优化师昨日数据-->
    <basic-container>
      <div class="welLabel">账户运营人昨日数据 <span class="lastDayStyle">({{ yesterday }})</span></div>
      <div>
        <el-table :default-sort = "{prop: 'cost', order: 'descending'}" :data="accountOpDataList" stripe style="width: 100%" height="250">
          <el-table-column prop="operatorName" label="运营人"/>
          <el-table-column prop="installs" label="安装" sortable :sort-method="(a,b)=>{return a.installs[0] - b.installs[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.installs[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.installsIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.installsIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="installsIncrease" label="涨幅" sortable :sort-method="(a,b)=>{return a.installsIncrease - b.installsIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.installsIncrease)}">
                {{ scope.row.installsIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="花费" sortable :sort-method="(a,b)=>{return a.cost[0] - b.cost[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.cost[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.costIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.costIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="costIncrease" label="涨幅" sortable :sort-method="(a,b)=>{return a.costIncrease - b.costIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.costIncrease)}">
                {{ scope.row.costIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </basic-container>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import Moment from "moment";
import {mapGetters} from "vuex";
import { queryOfferDaysPerformance, queryAccountDaysPerformance, queryAccountOpDaysPerformance } from "@/api/wel/ocindex";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {findByProp, findArray} from "@/util/util";

export default {
  name: "ocIndexLeft",
  data() {
    return {
      yesterday: '',
      offerInfo: null,
      offerStatus: [
        {label: '草稿', value: 0},
        {label: '活跃', value: 1},
        {label: '停止', value: 2},
        {label: '删除', value: 3}
      ],
      accountDataList: [],
      accountOpDataList: [],
    }
  },
  //测试echarts初始化
  created() {
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo","offer"]),
  },
  watch: {
    offer: {
      deep: true,
      handler(val, old) {
        if(val == '' || val == old) {
          return;
        }
        this.$nextTick(() => {
          this.init();
        })
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    })
  },
  methods: {
    getOfferStatusText() {
      if(this.offerInfo != null) {
        return findByProp(this.offerStatus,this.offerInfo.status);
      } else {
        return '---';
      }
    },
    loadOfferInfo(offerId,success) {
      if(offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res)=>{
          success(res.data.data);
        }).catch(()=>{
          success(null);
        });
      }
    },
    getEchartsInst(eleName) {
      let ele = document.getElementById(eleName);
      let myInst = echarts.getInstanceByDom(ele);
      if(myInst) {
        return myInst;
      } else {
        return echarts.init(ele);
      }
    },
    init() {
      this.loadOfferInfo(this.offer,(offerInfo)=>{
        this.offerInfo = offerInfo;
      });
      //获取昨日时间
      this.yesterday = Moment(new Date()).subtract('1', 'days').format('YYYY-MM-DD');
      //订单折线图
      this.offerLineEcharts();
      this.accountYesterdayTable();
      this.accountOpYesterdayTable();
    },
    //订单折线图
    offerLineEcharts(data = null, initSelected) {
      let self = this;
      let days = 7;
      if(data == null) {
        queryOfferDaysPerformance({offerId: this.offer, days: days}).then((res)=>{
          if(res.data.success) {
            this.offerLineEcharts(res.data.data);
          }
        });
        return;
      }
      self.offerLineEchartsData = data;
      let offerLineEchartsLegend = ['曝光数', '点击数', '安装数', '花费'];
      if(initSelected == null) {
          initSelected = {'曝光数': false, '点击数': false, '安装数': true, '花费': true};
      }

      let chartData = {
        impressions: [],
        clicks: [],
        installs: [],
        cost: [],
        dayList: [],
        weekDayList: [],
      };
      // let weekDays = ['Sun','Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      let realDays = days;
      for(let d=0;d<realDays;d++) {
        chartData.impressions.push(0);
        chartData.clicks.push(0);
        chartData.installs.push(0);
        chartData.cost.push(0);
        let targetDate = Moment(new Date()).subtract(( realDays - d), 'days').format('YYYY-MM-DD');
        chartData.dayList.push(targetDate);
        // chartData.weekDayList.push(weekDays[(new Date(targetDate)).getDay()]);
        chartData.weekDayList.push(targetDate);
      }
      data.forEach((row)=>{
        let reportDate = new Date(row.reportDate);
        let idx = chartData.dayList.indexOf(Moment(reportDate).format('YYYY-MM-DD'));
        if(idx != -1) {
          chartData.impressions[idx] = row.impressions;
          chartData.clicks[idx] = row.clicks;
          chartData.installs[idx] = row.installs;
          chartData.cost[idx] = row.cost;
        }
      });

      let myChart = this.getEchartsInst('offerLine');
      if(self.offerLineEchartsSelectChanged == null) {
        self.offerLineEchartsSelectChanged = (params)=> {
          let selectedCount = 0;
          offerLineEchartsLegend.forEach((legendDataName)=>{
            if(params.selected[legendDataName]) {
              selectedCount ++;
            }
          });
          if(selectedCount <= 2) {
            return;
          }
          let newSelected = {};
          offerLineEchartsLegend.forEach((legendDataName)=>{
            if(params.name != legendDataName) {
              newSelected[legendDataName] = params.selected[legendDataName];
            } else {
              newSelected[legendDataName] = false;
            }
          })
          self.$nextTick(() => {
            self.offerLineEcharts(self.offerLineEchartsData,newSelected);
          })
          if(!self.postMessageDisable) {
            self.postMessageDisable = true;
            self.$message({
              message: '本图表最多只能选择两项指标显示！',
              type: 'warning',
              onClose: ()=>{
                self.postMessageDisable = false;
              }
            });
          }
        };
        myChart.on('legendselectchanged',self.offerLineEchartsSelectChanged);
      }
      let option;
      option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: offerLineEchartsLegend,
          selected: initSelected
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartData.weekDayList
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '曝光数',
            type: 'line',
            data: chartData.impressions,
          },
          {
            name: '点击数',
            type: 'line',
            data: chartData.clicks,
          },
          {
            name: '安装数',
            type: 'line',
            data: chartData.installs,
          },
          {
            name: '花费',
            type: 'line',
            data: chartData.cost,
          },
        ]
      };
      option && myChart.setOption(option);
    },
    calcIncRate(toVal, fromVal) {
      if(toVal == fromVal) {
        return 0;
      }
      if(fromVal == 0) {
        return 1;
      }
      if(toVal == 0) {
        return -1;
      }
      return (toVal - fromVal)/fromVal;
    },
    getIncText(incVal) {
      let sign = '';
      if(incVal > 0) {
        sign = '+';
      }
      if(incVal < 0) {
        sign = '-';
      }
      let midVal = Math.round(Math.abs(incVal) * 10000).toString();
      while(midVal.length < 3) {
        midVal = '0' + midVal;
      }
      return sign + midVal.substring(0,midVal.length - 2) + '.' + midVal.substring(midVal.length - 2) + '%';
    },
    accountYesterdayTable(data = null) {
      let days = 2;
      if (data == null) {
        queryAccountDaysPerformance({offerId: this.offer, days: days}).then((res) => {
          if (res.data.success) {
            this.accountYesterdayTable(res.data.data);
          }
        });
        return;
      }
      let yesterdayReportDate = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD');
      let theDayBeforeYesterdayReportDate = Moment(new Date()).subtract(2, 'days').format('YYYY-MM-DD');

      let resultDataList = [];
      data.forEach((row) => {
        let reportDate = Moment(new Date(row.reportDate)).format('YYYY-MM-DD');
        let rowDataIdx = findArray(resultDataList,row.accountId,'accountId');
        let rowData = null;
        if(rowDataIdx == -1) {
          rowData = {
            accountId: row.accountId,
            accountName: row.accountName,
            impressions: [0,0],
            clicks: [0,0],
            installs: [0,0],
            cost: [0,0],
          };
          resultDataList.push(rowData);
        } else {
          rowData = resultDataList[rowDataIdx];
        }
        if(reportDate == yesterdayReportDate) {
          rowData.impressions[0] = row.impressions;
          rowData.clicks[0] = row.clicks;
          rowData.installs[0] = row.installs;
          rowData.cost[0] = row.cost;
        }
        if(reportDate == theDayBeforeYesterdayReportDate) {
          rowData.impressions[1] = row.impressions;
          rowData.clicks[1] = row.clicks;
          rowData.installs[1] = row.installs;
          rowData.cost[1] = row.cost;
        }
      });
      resultDataList.forEach(row=>{
        row.installsIncrease = row.installs[0] - row.installs[1];
        row.costIncrease = row.cost[0] - row.cost[1];
      });
      resultDataList.sort((a,b)=>{
        if(a.cost[0] > b.cost[0]) {
          return -1;
        }
        if(a.cost[0] < b.cost[0]) {
          return 1;
        }
        if(a.installs[0] > b.installs[0]) {
          return -1;
        }
        if(a.installs[0] < b.installs[0]) {
          return 1;
        }
        return 0;
      });
      this.accountDataList = resultDataList;
    },
    accountOpYesterdayTable(data = null) {
      let days = 2;
      if (data == null) {
        queryAccountOpDaysPerformance({offerId: this.offer, days: days}).then((res) => {
          if (res.data.success) {
            this.accountOpYesterdayTable(res.data.data);
          }
        });
        return;
      }
      let yesterdayReportDate = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD');
      let theDayBeforeYesterdayReportDate = Moment(new Date()).subtract(2, 'days').format('YYYY-MM-DD');

      let resultDataList = [];
      data.forEach((row) => {
        let reportDate = Moment(new Date(row.reportDate)).format('YYYY-MM-DD');
        let rowDataIdx = findArray(resultDataList,row.operator,'operator');
        let rowData = null;
        if(rowDataIdx == -1) {
          rowData = {
            operator: row.operator,
            operatorName: row.operatorName,
            impressions: [0,0],
            clicks: [0,0],
            installs: [0,0],
            cost: [0,0],
          };
          resultDataList.push(rowData);
        } else {
          rowData = resultDataList[rowDataIdx];
        }
        if(reportDate == yesterdayReportDate) {
          rowData.impressions[0] = row.impressions;
          rowData.clicks[0] = row.clicks;
          rowData.installs[0] = row.installs;
          rowData.cost[0] = row.cost;
        }
        if(reportDate == theDayBeforeYesterdayReportDate) {
          rowData.impressions[1] = row.impressions;
          rowData.clicks[1] = row.clicks;
          rowData.installs[1] = row.installs;
          rowData.cost[1] = row.cost;
        }
      });
      resultDataList.forEach(row=>{
        row.installsIncrease = row.installs[0] - row.installs[1];
        row.costIncrease = row.cost[0] - row.cost[1];
      });
      resultDataList.sort((a,b)=>{
        if(a.cost[0] > b.cost[0]) {
          return -1;
        }
        if(a.cost[0] < b.cost[0]) {
          return 1;
        }
        if(a.installs[0] > b.installs[0]) {
          return -1;
        }
        if(a.installs[0] < b.installs[0]) {
          return 1;
        }
        return 0;
      });
      this.accountOpDataList = resultDataList;
    },
    valueColor(incVal) {
      return incVal > 0 ? '#1d953f' : incVal < 0 ? '#b22c46' : 'black';
    },
    valueArrowImage(incVal) {
      return incVal > 0 ? '/img/icon/rise.png' : incVal < 0 ? '/img/icon/down.png' : '';
    },
  }
}
</script>

<style scoped lang="scss">
.offer-warning {
  font-size: 13px;
  color: #409eff;
  margin-bottom: 18px;
}

.welLabel {
  font-size: 17px;
  font-weight: bold;
  color: #409eff;
  margin-left: 20px;
}

.lastDayStyle {
  color: black;
  font-size: 16px;
  margin-left: 15px;
}

.table-img {
  width: 17px;
  margin-left: 10px;
  height: 23px;

  img {
    width: 100%;
    height: 100%;
  }

}
</style>
